/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BadgeDialog.java
 *
 * Created on 17-Nov-2010, 22:22:11
 */

package TimeRecording.forms;

import TimeRecording.TimeRecordingView;
import TimeRecording.business.BadgeMaintenance;
import TimeRecording.tables.Badge;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author david
 */
public class BadgeDialog extends javax.swing.JDialog {

    private final static String GET_BADGES = "Badge.findAll";

    private final static Logger LOGGER = Logger.getLogger(
            BadgeDialog.class.getName());
    
    // <editor-fold defaultstate="collapsed" desc="selectedBadge + Getter & Setter">
    private Badge selectedBadge = null;

    public Badge getSelectedBadge() {
        return selectedBadge;
    }

    public void setSelectedBadge(Badge selectedBadge) {
        Badge oldSelectedBadge = this.selectedBadge;
        this.selectedBadge = selectedBadge;
        firePropertyChange("selectedBadge", oldSelectedBadge, selectedBadge);
        setBadgeSelected(selectedBadge != null);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="badgeSelected + Getter & Setter">
    private boolean badgeSelected = false;

    public boolean getBadgeSelected() {
        return badgeSelected;
    }

    public void setBadgeSelected(boolean badgeSelected) {
        boolean oldBadgeSelected = this.badgeSelected;
        this.badgeSelected = badgeSelected;
        firePropertyChange("badgeSelected", oldBadgeSelected, badgeSelected);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="entityManager Getter & Setter">
    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        EntityManager oldEntityManager = entityManager;
        this.entityManager = entityManager;
        firePropertyChange("entityManager", oldEntityManager, entityManager);
    } // </editor-fold>

    /** Creates new form BadgeDialog */
    public BadgeDialog(TimeRecordingView parent, boolean modal) {
        super(parent.getFrame(), modal);
        myParent = parent;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = myParent.getEntityManager();
        query = entityManager.createNamedQuery(GET_BADGES);
        badgeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        badgesPanel = new javax.swing.JScrollPane();
        badgesTable = new javax.swing.JTable();
        buttonPanel = new javax.swing.JPanel();
        newButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        badgesPanel.setName("badgesPanel"); // NOI18N

        badgesTable.setAutoCreateRowSorter(true);
        badgesTable.setName("badgesTable"); // NOI18N
        badgesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, badgeList, badgesTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${badgeId}"));
        columnBinding.setColumnName("Badge Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${employeeId}"));
        columnBinding.setColumnName("Employee Id");
        columnBinding.setColumnClass(TimeRecording.tables.Employee.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedBadge}"), badgesTable, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"));
        bindingGroup.addBinding(binding);

        badgesPanel.setViewportView(badgesTable);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(BadgeDialog.class);
        badgesTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        badgesTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("badgesTable.columnModel.title0")); // NOI18N
        badgesTable.getColumnModel().getColumn(1).setPreferredWidth(300);
        badgesTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("badgesTable.columnModel.title1")); // NOI18N

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 0, 8);
        getContentPane().add(badgesPanel, gridBagConstraints);

        buttonPanel.setName("buttonPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getActionMap(BadgeDialog.class, this);
        newButton.setAction(actionMap.get("newBadge")); // NOI18N
        newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
        newButton.setName("newButton"); // NOI18N
        buttonPanel.add(newButton);

        editButton.setAction(actionMap.get("editBadge")); // NOI18N
        editButton.setText(resourceMap.getString("editButton.text")); // NOI18N
        editButton.setName("editButton"); // NOI18N
        buttonPanel.add(editButton);

        deleteButton.setAction(actionMap.get("deleteBadge")); // NOI18N
        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        buttonPanel.add(deleteButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(buttonPanel, gridBagConstraints);

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-408)/2, (screenSize.height-391)/2, 408, 391);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        
        // Make a back end call to retro-fit employee IDs to
        // clocking records made against unallocated badges
        entityManager.getTransaction().begin();
        new BadgeMaintenance(entityManager).housekeeping(null);
        entityManager.getTransaction().commit();

        myParent.hideBadgesDialog();
    }//GEN-LAST:event_formWindowClosing

    @SuppressWarnings("unchecked")
    @Action
    public void newBadge() {

        // Create a new badge and allow user to edit it
        Badge newBadge = new Badge();
        BadgeEditor editor = new BadgeEditor(this);
        editor.setBadge(newBadge);
        editor.setVisible(true);

        // If user has bottled the editor then just ditch the new badge
        if (!editor.getSaved()) {
            return;
        }

        // Persist the new badge
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(newBadge);
            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error creating badge", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }

        // Refresh the list
        badgeList.clear();
        badgeList.addAll((List<Badge>)query.getResultList());

        // Select the newly created row
        for (int row = 0; row < badgesTable.getRowCount(); row++) {
            if (badgesTable.getValueAt(row, 0).
                    equals(newBadge.getBadgeId())) {
                badgesTable.scrollRectToVisible(
                        badgesTable.getCellRect(row, 0, true));
                badgesTable.setRowSelectionInterval(row, row);
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Action(enabledProperty = "badgeSelected")
    public void deleteBadge() {

        if (JOptionPane.showConfirmDialog(this,
                "Are you sure you wish to delete the badge",
                "Delete Badge",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
            return;
        }
        
        try {
            entityManager.getTransaction().begin();
            entityManager.remove(selectedBadge);
            entityManager.getTransaction().commit();

            // Refresh the list
            badgeList.clear();
            badgeList.addAll((List<Badge>)query.getResultList());

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error deleting badge", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

    @Action(enabledProperty = "badgeSelected")
    public void editBadge() {

        // Create a new badge and allow user to edit it
        BadgeEditor editor = new BadgeEditor(this);
        editor.setBadge(getSelectedBadge());
        editor.setVisible(true);

        // If user has bottled the editor then just ditch the new badge
        if (!editor.getSaved()) {
            entityManager.refresh(getSelectedBadge());
            return;
        }

        // Persist the new badge
        try {
            entityManager.getTransaction().begin();
            entityManager.merge(getSelectedBadge());
            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error editing badge", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<TimeRecording.tables.Badge> badgeList;
    private javax.swing.JScrollPane badgesPanel;
    private javax.swing.JTable badgesTable;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton newButton;
    private javax.persistence.Query query;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private TimeRecordingView myParent;
}
